<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form
        :model="where"
        label-width="100px"
        class="ele-form-search"
        @keyup.enter.native="reload"
        @submit.native.prevent>
        <el-row :gutter="15">
          <el-col :lg="6" :md="12">
            <el-form-item label="门店名称:">
              <el-input
                clearable
                v-model="where.store_keyword"
                placeholder="请输入门店名称或编号">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="所属商户:">
              <el-input
                clearable
                v-model="where.merchant_keyword"
                placeholder="请输入商户名称">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="门店状态:">
              <el-select
                clearable
                v-model="where.status"
                placeholder="请选择状态"
                class="ele-fluid">
                <el-option label="正常" :value="1"></el-option>
                <el-option label="禁用" :value="0"></el-option>
                <el-option label="审核中" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <div class="ele-form-actions">
              <el-button
                type="primary"
                icon="el-icon-search"
                class="ele-btn-icon"
                @click="reload">查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>


      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :where="where"
        :datasource="url"
        :columns="columns"
        :selection.sync="selection"
        height="calc(100vh - 480px)"
        cache-key="chuandaoStoreTable">
        
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <el-alert
            title="门店管理说明"
            type="info"
            :closable="false"
            style="margin-bottom: 10px;">
            <template slot="title">
              <i class="el-icon-info"></i>
              门店信息由船到平台自动同步，暂不支持手动创建。如需新增门店，请在船到平台操作后等待同步。
            </template>
          </el-alert>
          
          <el-button
            size="small"
            type="success"
            icon="el-icon-download"
            class="ele-btn-icon"
            @click="exportData">{{ exportButtonText }}
          </el-button>
        </template>

        <!-- 门店信息列 -->
        <template slot="store_info" slot-scope="{row}">
          <div class="store-info">
            <div class="store-main">
              <div class="store-name">{{ row.store_name }}</div>
              <div class="store-code">门店编号: {{ row.store_code }}</div>
            </div>
            <div class="store-id">ID: {{ row.id }}</div>
          </div>
        </template>

        <!-- 商户信息列 -->
        <template slot="merchant_info" slot-scope="{row}">
          <div class="merchant-info">
            <div class="merchant-name">{{ row.merchant_name }}</div>
            <div class="merchant-mobile">{{ row.merchant_mobile }}</div>
          </div>
        </template>

        <!-- 地址列 -->
        <template slot="address" slot-scope="{row}">
          <div class="address-info">
            <div class="address-main">{{ row.address }}</div>
            <div class="coordinates" v-if="row.longitude && row.latitude">
              <i class="el-icon-location"></i>
              {{ row.longitude }}, {{ row.latitude }}
            </div>
          </div>
        </template>

        <!-- 状态列 -->
        <template slot="status" slot-scope="{row}">
          <el-tag :type="getStatusColor(row.status)" size="small">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>

        <!-- 联系方式列 -->
        <template slot="contact" slot-scope="{row}">
          <div class="contact-info">
            <div v-if="row.contact_name" class="contact-name">
              <i class="el-icon-user"></i>
              {{ row.contact_name }}
            </div>
            <div v-if="row.contact_phone" class="contact-phone">
              <i class="el-icon-phone"></i>
              {{ row.contact_phone }}
            </div>
          </div>
        </template>

        <!-- 创建时间列 -->
        <template slot="created_at" slot-scope="{row}">
          {{ formatDate(row.created_at) }}
        </template>

        <!-- 操作列 -->
        <template slot="action" slot-scope="{row}">
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="showStoreDetail(row)">详情
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-location-information"
            @click="showStoreLocation(row)">位置
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-tickets"
            @click="viewStoreOrders(row)">订单
          </el-button>
        </template>
      </ele-pro-table>
    </el-card>

    <!-- 门店详情弹窗 -->
    <el-dialog
      title="门店详情"
      :visible.sync="detailVisible"
      width="800px"
      :close-on-click-modal="false">
      <div v-if="currentStore">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="门店ID">{{ currentStore.id }}</el-descriptions-item>
          <el-descriptions-item label="门店编号">{{ currentStore.store_code }}</el-descriptions-item>
          <el-descriptions-item label="门店名称" :span="2">{{ currentStore.store_name }}</el-descriptions-item>
          <el-descriptions-item label="所属商户">{{ currentStore.merchant_name }}</el-descriptions-item>
          <el-descriptions-item label="商户手机">{{ currentStore.merchant_mobile }}</el-descriptions-item>
          <el-descriptions-item label="门店地址" :span="2">{{ currentStore.address }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ currentStore.contact_name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentStore.contact_phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="经度">{{ currentStore.longitude || '-' }}</el-descriptions-item>
          <el-descriptions-item label="纬度">{{ currentStore.latitude || '-' }}</el-descriptions-item>
          <el-descriptions-item label="门店状态">
            <el-tag :type="getStatusColor(currentStore.status)" size="small">
              {{ getStatusText(currentStore.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="船到门店ID">{{ currentStore.origin_id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(currentStore.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(currentStore.updated_at) }}</el-descriptions-item>
          <el-descriptions-item label="营业时间" :span="2">
            {{ currentStore.business_hours || '暂无营业时间信息' }}
          </el-descriptions-item>
          <el-descriptions-item label="门店描述" :span="2">
            {{ currentStore.description || '暂无门店描述' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 门店位置弹窗 -->
    <el-dialog
      title="门店位置"
      :visible.sync="locationVisible"
      width="900px"
      :close-on-click-modal="false">
      <div v-if="currentStore">
        <!-- 地址信息 -->
        <div class="location-header">
          <div class="location-info">
            <h3>{{ currentStore.store_name }}</h3>
            <p class="address">
              <i class="el-icon-location-outline"></i>
              {{ currentStore.address }}
            </p>
            <div class="coordinates" v-if="currentStore.longitude && currentStore.latitude">
              <span class="coord-item">
                <strong>经度:</strong> {{ currentStore.longitude }}
              </span>
              <span class="coord-item">
                <strong>纬度:</strong> {{ currentStore.latitude }}
              </span>
            </div>
          </div>
        </div>

        <!-- 腾讯地图区域 -->
        <div class="map-container">
          <!-- 地图提示信息 -->
          <div class="map-tip" v-if="currentStore && currentStore.longitude && currentStore.latitude">
            <i class="el-icon-location"></i>
            <span>{{ currentStore.store_name }} 的位置已在地图上标出</span>
          </div>

          <tencent-map
            :center="mapCenter"
            :zoom="16"
            :markers="mapMarkers"
            height="320px"
            @map-ready="onMapReady"
            @marker-click="onMarkerClick"
            @map-click="onMapClick">
          </tencent-map>

          <!-- 无坐标提示 -->
          <div class="no-location-tip" v-if="currentStore && (!currentStore.longitude || !currentStore.latitude)">
            <i class="el-icon-warning"></i>
            <span>该门店暂无坐标信息，显示默认位置</span>
          </div>
        </div>

        <!-- 位置操作 -->
        <div class="location-actions">
          <el-button
            type="success"
            icon="el-icon-location-information"
            @click="focusOnStore"
            v-if="currentStore && currentStore.longitude && currentStore.latitude">
            定位门店
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-map-location"
            @click="openMapNavigation">
            导航到门店
          </el-button>
          <el-button
            icon="el-icon-copy-document"
            @click="copyCoordinates">
            复制坐标
          </el-button>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="locationVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 门店订单弹窗 -->
    <el-dialog
      :title="`门店订单 - ${currentStore ? currentStore.store_name : ''}`"
      :visible.sync="ordersVisible"
      width="90%"
      :close-on-click-modal="false"
      @close="handleOrdersDialogClose">

      <!-- 搜索条件 -->
      <div class="orders-search" style="margin-bottom: 20px;">
        <el-form :inline="true" size="small">
          <el-form-item label="订单状态">
            <el-select v-model="ordersWhere.status" placeholder="全部状态" clearable style="width: 120px;">
              <el-option label="待接单" :value="1"></el-option>
              <el-option label="已接单" :value="2"></el-option>
              <el-option label="配送中" :value="3"></el-option>
              <el-option label="已完成" :value="4"></el-option>
              <el-option label="已取消" :value="5"></el-option>
              <el-option label="已超时" :value="6"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker
              v-model="ordersWhere.start_date"
              type="date"
              placeholder="选择日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 140px;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker
              v-model="ordersWhere.end_date"
              type="date"
              placeholder="选择日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 140px;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="订单号">
            <el-input
              v-model="ordersWhere.order_no"
              placeholder="输入订单号"
              style="width: 150px;"
              @keyup.enter.native="handleOrdersSearch"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleOrdersSearch" :loading="ordersLoading">
              <i class="el-icon-search"></i> 搜索
            </el-button>
            <el-button @click="resetOrdersSearch" :disabled="ordersLoading">
              <i class="el-icon-refresh"></i> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 订单列表 -->
      <el-table
        :data="orders"
        v-loading="ordersLoading"
        element-loading-text="正在加载订单数据..."
        border
        stripe
        style="width: 100%"
        :empty-text="orders.length === 0 && !ordersLoading ? '暂无订单数据' : ''"
        height="400">
        <el-table-column prop="order_no" label="订单号" width="180">
          <template slot-scope="scope">
            <div>{{ scope.row.order_no }}</div>
            <div style="font-size: 12px; color: #999;" v-if="scope.row.chuandao_order_no">
              船到: {{ scope.row.chuandao_order_no }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用户信息" width="150">
          <template slot-scope="scope">
            <div>{{ scope.row.user_info.nickname }}</div>
            <div style="font-size: 12px; color: #666;">{{ scope.row.user_info.phone }}</div>
          </template>
        </el-table-column>
        <el-table-column label="商品信息" width="120">
          <template slot-scope="scope">
            <div>{{ scope.row.goods_info.goods_type }}</div>
            <div style="font-size: 12px; color: #666;">{{ scope.row.goods_info.weight }}kg</div>
          </template>
        </el-table-column>
        <el-table-column label="地址信息" min-width="200">
          <template slot-scope="scope">
            <div style="font-size: 12px;">
              <div><strong>取:</strong> {{ scope.row.address_info.pickup_address }}</div>
              <div><strong>送:</strong> {{ scope.row.address_info.delivery_address }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" width="120">
          <template slot-scope="scope">
            <div>
              <el-tag :type="getOrderStatusColor(scope.row.status)" size="small">
                {{ getOrderStatusText(scope.row.status) }}
              </el-tag>
            </div>
            <div style="font-size: 12px; color: #999; margin-top: 2px;" v-if="scope.row.chuandao_status_text">
              船到: {{ scope.row.chuandao_status_text }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="配送平台" width="100">
          <template slot-scope="scope">
            <el-tag size="small" :type="scope.row.platform_type ? 'success' : 'info'">
              {{ getPlatformText(scope.row.platform_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120">
          <template slot-scope="scope">
            <div>配送: ¥{{ formatAmount(scope.row.delivery_fee) }}</div>
            <div>总计: ¥{{ formatAmount(scope.row.total_amount) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="150">
          <template slot-scope="scope">
            {{ formatDate(scope.row.create_time) }}
          </template>
        </el-table-column>
        <!-- 移除了重复的详情按钮，订单信息已在列表中显示 -->
      </el-table>

      <!-- 分页和统计信息 -->
      <div style="margin-top: 20px;">
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <div style="color: #666; font-size: 14px;">
            <span v-if="ordersTotal > 0">
              共 {{ ordersTotal }} 条订单，当前显示第 {{ (ordersPage - 1) * ordersLimit + 1 }} - {{ Math.min(ordersPage * ordersLimit, ordersTotal) }} 条
            </span>
            <span v-else>暂无数据</span>
          </div>
          <el-pagination
            @current-change="handleOrdersPageChange"
            :current-page="ordersPage"
            :page-size="ordersLimit"
            layout="prev, pager, next, jumper"
            :total="ordersTotal"
            :disabled="ordersLoading"
            small>
          </el-pagination>
        </div>
      </div>

      <div slot="footer">
        <el-button @click="ordersVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 已移除重复的订单详情弹窗，订单信息已在列表中充分展示 -->
  </div>
</template>

<script>
import { getStoreOrders, exportStoreData } from '@/api/chuandao';
import TencentMap from '@/components/TencentMap.vue';

export default {
  name: 'ChuandaoStoreIndex',
  components: {
    TencentMap
  },
  data() {
    return {
      // 表格配置
      url: 'chuandao/store/list',
      where: {
        store_keyword: '',
        merchant_keyword: '',
        status: null
      },
      
      columns: [
        {
          columnKey: 'selection',
          type: 'selection',
          width: 45,
          align: 'center'
        },
        {
          prop: 'id',
          label: 'ID',
          width: 80,
          align: 'center'
        },
        {
          prop: 'store_info',
          label: '门店信息',
          slot: 'store_info',
          minWidth: 200
        },
        {
          prop: 'merchant_info',
          label: '所属商户',
          slot: 'merchant_info',
          minWidth: 160
        },
        {
          prop: 'address',
          label: '门店地址',
          slot: 'address',
          minWidth: 200,
          showOverflowTooltip: true
        },
        {
          prop: 'contact',
          label: '联系方式',
          slot: 'contact',
          width: 140
        },
        {
          prop: 'status',
          label: '状态',
          slot: 'status',
          width: 80,
          align: 'center'
        },
        {
          prop: 'created_at',
          label: '创建时间',
          slot: 'created_at',
          width: 160
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 150,
          slot: 'action',
          align: 'center'
        }
      ],
      selection: [],

      // 弹窗状态
      detailVisible: false,
      locationVisible: false,
      ordersVisible: false,

      // 当前门店
      currentStore: null,
      currentOrder: null,

      // 加载状态

      // 地图相关数据
      mapCenter: { lat: 39.908823, lng: 116.397470 }, // 默认中心点
      mapMarkers: [], // 地图标记点
      mapInstance: null, // 地图实例
      focusExecuted: false, // 标记是否已经执行过自动聚焦

      // 订单相关数据
      orders: [],
      ordersLoading: false,
      ordersTotal: 0,
      ordersPage: 1,
      ordersLimit: 10,
      ordersWhere: {
        status: null,
        start_date: '',
        end_date: '',
        order_no: ''
      }
    };
  },

  computed: {
    // 导出按钮文本（根据选中状态动态显示）
    exportButtonText() {
      if (this.selection && this.selection.length > 0) {
        return `导出选中数据 (${this.selection.length}条)`;
      } else {
        return '导出数据';
      }
    }
  },

  methods: {
    // 重新加载表格
    reload() {
      this.$refs.table.reload();
    },

    // 重置搜索
    reset() {
      this.where = {
        store_keyword: '',
        merchant_keyword: '',
        status: null
      };
      this.reload();
    },


    // 显示门店详情
    showStoreDetail(row) {
      this.currentStore = row;
      this.detailVisible = true;
    },

    // 显示门店位置
    showStoreLocation(row) {
      this.currentStore = row;
      this.locationVisible = true;
      // 重置聚焦标记，允许新门店的自动聚焦
      this.focusExecuted = false;

      // 设置地图中心点和标记
      if (row.longitude && row.latitude) {
        this.mapCenter = {
          lat: parseFloat(row.latitude),
          lng: parseFloat(row.longitude)
        };

        this.mapMarkers = [{
          id: row.id,
          lat: parseFloat(row.latitude),
          lng: parseFloat(row.longitude),
          title: row.store_name,
          address: row.address,
          description: `门店编号: ${row.store_code}`,
          infoContent: `
            <div class="map-info-window">
              <h4>${row.store_name}</h4>
              <p><i class="el-icon-location-outline"></i> ${row.address}</p>
              <p><i class="el-icon-office-building"></i> 门店编号: ${row.store_code}</p>
              <p><i class="el-icon-phone"></i> 联系电话: ${row.mobile || '暂无'}</p>
            </div>
          `
        }];
      } else {
        // 如果没有坐标，使用默认位置
        this.mapCenter = { lat: 39.908823, lng: 116.397470 };
        this.mapMarkers = [];
      }
    },


    // 查看门店订单
    viewStoreOrders(row) {
      this.currentStore = row;
      this.ordersVisible = true;
      this.loadStoreOrders();
    },




    // 打开地图导航
    openMapNavigation() {
      if (!this.currentStore.longitude || !this.currentStore.latitude) {
        this.$message.warning('该门店缺少坐标信息，无法导航');
        return;
      }

      // 提供多种导航选择
      this.$confirm('选择导航方式', '导航到门店', {
        distinguishCancelAndClose: true,
        confirmButtonText: '腾讯地图',
        cancelButtonText: '高德地图',
        type: 'info'
      }).then(() => {
        // 腾讯地图导航
        const tencentUrl = `https://apis.map.qq.com/uri/v1/routeplan?type=drive&to=${this.currentStore.store_name}&tocoord=${this.currentStore.latitude},${this.currentStore.longitude}&policy=1`;
        window.open(tencentUrl, '_blank');
      }).catch(action => {
        if (action === 'cancel') {
          // 高德地图导航
          const amapUrl = `https://uri.amap.com/navigation?to=${this.currentStore.longitude},${this.currentStore.latitude},${this.currentStore.store_name}`;
          window.open(amapUrl, '_blank');
        }
      });
    },

    // 复制坐标
    async copyCoordinates() {
      if (!this.currentStore.longitude || !this.currentStore.latitude) {
        this.$message.warning('该门店缺少坐标信息');
        return;
      }

      const coordinates = `${this.currentStore.longitude},${this.currentStore.latitude}`;

      try {
        // 优先使用现代的Clipboard API
        if (navigator.clipboard && window.isSecureContext) {
          await navigator.clipboard.writeText(coordinates);
        } else {
          // 降级到传统方法
          const textarea = document.createElement('textarea');
          textarea.value = coordinates;
          document.body.appendChild(textarea);
          textarea.select();
          document.execCommand('copy');
          document.body.removeChild(textarea);
        }
        this.$message.success('坐标已复制到剪贴板');
      } catch (error) {
        console.error('复制失败:', error);
        this.$message.error('复制失败，请手动复制坐标');
      }
    },

    // 导出数据（双模式支持）
    async exportData() {
      try {
        // 判断导出模式
        const hasSelection = this.selection && this.selection.length > 0;
        const mode = hasSelection ? 'selected' : 'filter';
        const recordCount = hasSelection ? this.selection.length : '全部筛选结果';
        
        // 显示加载提示
        const loading = this.$loading({
          lock: true,
          text: `正在导出门店数据（${recordCount}条），请稍候...`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        let exportParams = {};

        if (mode === 'selected') {
          // 选中记录模式
          const selectedIds = this.selection.map(item => item.id).filter(id => id);
          
          if (selectedIds.length === 0) {
            loading.close();
            this.$message.warning('请先选择要导出的门店记录');
            return;
          }
          
          // 限制导出数量
          if (selectedIds.length > 5000) {
            loading.close();
            this.$message.error(`单次最多可导出5000条记录，当前选中${selectedIds.length}条`);
            return;
          }
          
          exportParams = {
            mode: 'selected',
            ids: selectedIds
          };
          
        } else {
          // 筛选条件模式（原有逻辑）
          exportParams = {
            mode: 'filter',
            store_keyword: this.where.store_keyword,
            merchant_keyword: this.where.merchant_keyword,
            status: this.where.status
          };
          
          // 过滤空值参数
          Object.keys(exportParams).forEach(key => {
            if (exportParams[key] === '' || exportParams[key] === null || exportParams[key] === undefined) {
              delete exportParams[key];
            }
          });
        }

        // 调用导出接口
        const response = await exportStoreData(exportParams);
        
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response]));
        const link = document.createElement('a');
        link.href = url;
        
        // 生成文件名
        const date = new Date();
        const dateStr = date.getFullYear() + '-' + 
                       String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                       String(date.getDate()).padStart(2, '0') + '_' +
                       String(date.getHours()).padStart(2, '0') + '-' +
                       String(date.getMinutes()).padStart(2, '0') + '-' +
                       String(date.getSeconds()).padStart(2, '0');
        
        const modeText = mode === 'selected' ? `选中${this.selection.length}条` : '筛选条件';
        link.download = `船到门店列表_${modeText}_${dateStr}.csv`;
        document.body.appendChild(link);
        link.click();
        
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        
        loading.close();
        
        // 显示成功提示
        const successMessage = mode === 'selected' 
          ? `成功导出${this.selection.length}条选中门店数据！` 
          : '门店数据导出成功！';
          
        this.$message({
          type: 'success',
          message: successMessage,
          duration: 3000
        });

      } catch (error) {
        console.error('导出失败:', error);
        
        // 关闭加载提示
        this.$loading().close();
        
        // 显示错误提示
        let errorMessage = '导出失败，请稍后重试';
        
        if (error.response) {
          if (error.response.status === 403) {
            errorMessage = '没有权限导出门店数据';
          } else if (error.response.status === 500) {
            errorMessage = '服务器错误，导出失败';
          } else {
            errorMessage = error.response.data?.message || errorMessage;
          }
        } else if (error.request) {
          errorMessage = '网络连接失败，请检查网络';
        }
        
        this.$message({
          type: 'error',
          message: errorMessage,
          duration: 5000
        });
      }
    },

    // 地图准备就绪事件
    onMapReady(mapInstance) {
      this.mapInstance = mapInstance;
      console.log('地图加载完成', mapInstance);

      // 如果有门店坐标且还没有执行过自动聚焦，则自动适配地图视野
      if (this.currentStore && this.currentStore.longitude && this.currentStore.latitude && !this.focusExecuted) {
        // 延迟一下确保标记已添加
        setTimeout(() => {
          this.focusOnStore(true); // 传入true表示是自动聚焦
        }, 1000);
      }
    },

    // 地图标记点击事件
    onMarkerClick(markerData) {
      console.log('标记点击:', markerData);
      this.$message.info(`点击了门店: ${markerData.title}`);
    },

    // 地图点击事件
    onMapClick(position) {
      console.log('地图点击:', position);
    },

    // 聚焦到门店位置
    focusOnStore(isAutoFocus = false) {
      if (this.mapInstance && this.currentStore && this.currentStore.longitude && this.currentStore.latitude) {
        // 如果是自动聚焦且已经执行过，则跳过
        if (isAutoFocus && this.focusExecuted) {
          return;
        }

        // 设置地图中心并添加缩放动画
        this.mapInstance.easeTo({
          center: new TMap.LatLng(parseFloat(this.currentStore.latitude), parseFloat(this.currentStore.longitude)),
          zoom: 17,
          duration: 1000
        });

        // 显示成功提示
        this.$message({
          message: `已定位到 ${this.currentStore.store_name}`,
          type: 'success',
          duration: 2000
        });

        // 如果是自动聚焦，标记已执行
        if (isAutoFocus) {
          this.focusExecuted = true;
        }
      }
    },

    // 加载门店订单列表
    loadStoreOrders() {
      if (!this.currentStore) {
        this.$message.warning('请先选择门店');
        return;
      }

      this.ordersLoading = true;
      const params = {
        page: this.ordersPage,
        limit: this.ordersLimit,
        ...this.ordersWhere
      };

      // 过滤空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key];
        }
      });

      getStoreOrders(this.currentStore.id, params).then(res => {
        if (res.code === 200) {
          this.orders = res.data.orders.data || [];
          this.ordersTotal = res.data.orders.total || 0;

          if (this.orders.length === 0 && this.ordersPage === 1) {
            this.$message.info('该门店暂无订单数据');
          }
        } else {
          this.orders = [];
          this.ordersTotal = 0;
          this.$message.error(res.message || '获取门店订单失败');
        }
      }).catch(error => {
        console.error('获取门店订单失败:', error);
        this.orders = [];
        this.ordersTotal = 0;

        if (error.response && error.response.status === 404) {
          this.$message.error('门店不存在或已被删除');
        } else if (error.response && error.response.status === 403) {
          this.$message.error('没有权限访问该门店订单');
        } else {
          this.$message.error('网络错误，请检查网络连接后重试');
        }
      }).finally(() => {
        this.ordersLoading = false;
      });
    },

    // 处理订单搜索
    handleOrdersSearch() {
      // 验证日期范围
      if (this.ordersWhere.start_date && this.ordersWhere.end_date) {
        const startDate = new Date(this.ordersWhere.start_date);
        const endDate = new Date(this.ordersWhere.end_date);

        if (startDate > endDate) {
          this.$message.warning('开始日期不能大于结束日期');
          return;
        }

        // 检查日期范围是否过大（超过1年）
        const diffTime = Math.abs(endDate - startDate);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        if (diffDays > 365) {
          this.$message.warning('查询日期范围不能超过1年');
          return;
        }
      }

      this.ordersPage = 1; // 重置到第一页
      this.loadStoreOrders();
    },

    // 重置订单搜索
    resetOrdersSearch() {
      this.ordersWhere = {
        status: null,
        start_date: '',
        end_date: '',
        order_no: ''
      };
      this.ordersPage = 1;
      this.loadStoreOrders();
    },

    // 订单分页变化
    handleOrdersPageChange(page) {
      this.ordersPage = page;
      this.loadStoreOrders();
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '正常',
        0: '禁用',
        2: '审核中'
      };
      return statusMap[status] || '未知';
    },

    // 获取状态颜色
    getStatusColor(status) {
      const colorMap = {
        1: 'success',
        0: 'danger',
        2: 'warning'
      };
      return colorMap[status] || '';
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '-';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },

    // 获取订单状态文本
    getOrderStatusText(status) {
      const statusMap = {
        1: '待接单',
        2: '已接单',
        3: '配送中',
        4: '已完成',
        5: '已取消',
        6: '已超时'
      };
      return statusMap[status] || '未知状态';
    },

    // 获取订单状态颜色
    getOrderStatusColor(status) {
      const colorMap = {
        1: 'warning',
        2: 'primary',
        3: 'info',
        4: 'success',
        5: 'danger',
        6: 'danger'
      };
      return colorMap[status] || 'info';
    },

    // 获取平台文本
    getPlatformText(platformType) {
      const platformMap = {
        'DD': '达达',
        'FN': '蜂鸟',
        'SS': '闪送',
        'UU': 'UU跑腿',
        'SF': '顺丰',
        'GXD': '裹小递',
        'XZWM': '小镇外卖',
        'MTQK': '美团快速达',
        'KFW': '快服务',
        'SFYX': '顺丰优享'
      };
      return platformMap[platformType] || platformType || '未知平台';
    },

    // 格式化金额
    formatAmount(amount) {
      return amount ? parseFloat(amount).toFixed(2) : '0.00';
    },

    // 处理订单弹窗关闭
    handleOrdersDialogClose() {
      // 重置搜索条件和分页
      this.ordersWhere = {
        status: null,
        start_date: '',
        end_date: '',
        order_no: ''
      };
      this.ordersPage = 1;
      this.orders = [];
      this.ordersTotal = 0;
      this.currentStore = null;
    },

    // 已移除 viewOrderDetail 方法，不再需要重复的订单详情弹窗
  }
};
</script>

<style scoped>
.ele-form-search {
  margin-bottom: 20px;
}


/* 表格内容样式 */
.store-info {
  display: flex;
  flex-direction: column;
}

.store-main {
  margin-bottom: 5px;
}

.store-name {
  font-weight: 500;
  margin-bottom: 3px;
}

.store-code {
  font-size: 12px;
  color: #909399;
}

.store-id {
  font-size: 12px;
  color: #C0C4CC;
}

.merchant-info {
  display: flex;
  flex-direction: column;
}

.merchant-name {
  font-weight: 500;
  margin-bottom: 2px;
}

.merchant-mobile {
  font-size: 12px;
  color: #909399;
}

.address-info {
  display: flex;
  flex-direction: column;
}

.address-main {
  margin-bottom: 3px;
}

.coordinates {
  font-size: 12px;
  color: #909399;
}

.contact-info {
  display: flex;
  flex-direction: column;
}

.contact-name,
.contact-phone {
  display: flex;
  align-items: center;
  font-size: 12px;
  margin-bottom: 2px;
}

.contact-name i,
.contact-phone i {
  margin-right: 4px;
  width: 14px;
}

/* 位置弹窗样式 */
.location-header {
  margin-bottom: 20px;
}

.location-info h3 {
  margin: 0 0 10px 0;
  color: #303133;
}

.location-info .address {
  display: flex;
  align-items: center;
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.location-info .address i {
  margin-right: 8px;
}

.coordinates {
  display: flex;
  gap: 20px;
}

.coord-item {
  color: #909399;
  font-size: 13px;
}

.map-container {
  margin-bottom: 20px;
  border: 1px solid #DCDFE6;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.map-container:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.map-tip {
  background: linear-gradient(135deg, #67C23A, #85CE61);
  color: white;
  padding: 8px 12px;
  font-size: 13px;
  display: flex;
  align-items: center;
  border-radius: 4px 4px 0 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.map-tip i {
  margin-right: 6px;
  font-size: 14px;
  animation: pulse 2s infinite;
}

.no-location-tip {
  background: linear-gradient(135deg, #F56C6C, #F78989);
  color: white;
  padding: 8px 12px;
  font-size: 13px;
  display: flex;
  align-items: center;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.no-location-tip i {
  margin-right: 6px;
  font-size: 14px;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.map-placeholder {
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #F5F7FA;
  color: #909399;
}

.map-placeholder i {
  font-size: 48px;
  margin-bottom: 15px;
}

.map-placeholder p {
  margin: 0;
  font-size: 16px;
}

.map-note {
  font-size: 12px !important;
  margin-top: 8px !important;
}

.location-actions {
  text-align: center;
  display: flex;
  gap: 10px;
  justify-content: center;
  flex-wrap: wrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .location-actions {
    flex-direction: column;
    align-items: center;
  }

  .location-actions .el-button {
    width: 100%;
    max-width: 200px;
  }

  .coordinates {
    flex-direction: column;
    gap: 10px;
  }

  .location-info h3 {
    font-size: 16px;
  }

  .location-info .address {
    font-size: 13px;
  }
}

.location-actions .el-button {
  margin: 0 10px;
}

/* 操作按钮样式 */
.el-button--text {
  padding: 0;
  margin-right: 10px;
}

.el-button--text:last-child {
  margin-right: 0;
}

/* 下拉菜单样式 */
.el-dropdown {
  vertical-align: top;
}

/* 响应式调整 */
@media (max-width: 768px) {
}

/* 表单项间距 */
.el-form-item {
  margin-bottom: 15px;
}

/* 工具栏样式 */
.ele-form-actions {
  text-align: left;
}

/* 标签样式调整 */
.el-tag {
  border-radius: 4px;
}

/* 提示信息样式 */
.el-alert {
  margin-bottom: 15px;
}

.el-alert .el-alert__title {
  display: flex;
  align-items: center;
}

.el-alert .el-alert__title i {
  margin-right: 8px;
}

/* 订单弹窗样式优化 */
.orders-search {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
}

.orders-search .el-form-item {
  margin-bottom: 10px;
}

/* 订单表格样式优化 */
.el-table .cell {
  word-break: break-word;
  line-height: 1.4;
}

/* 订单状态标签样式 */
.el-tag {
  margin: 2px 0;
  font-weight: 500;
}

/* 订单详情弹窗样式 */
.el-descriptions {
  margin-bottom: 20px;
}

.el-descriptions-item__label {
  font-weight: bold;
  color: #606266;
  background-color: #fafafa;
}

.el-descriptions-item__content {
  color: #303133;
}

/* 加载状态优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.9);
}

.el-loading-spinner .el-loading-text {
  color: #409eff;
  font-weight: 500;
}

/* 空数据提示样式 */
.el-table__empty-text {
  color: #909399;
  font-size: 14px;
  padding: 40px 0;
}

/* 搜索按钮样式 */
.el-button + .el-button {
  margin-left: 8px;
}

.el-button .el-icon-search,
.el-button .el-icon-refresh {
  margin-right: 4px;
}

/* 分页样式优化 */
.el-pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.el-pagination .el-pagination__total {
  margin-right: auto;
  color: #606266;
  font-size: 13px;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .orders-search .el-form-item {
    display: block;
    margin-right: 0;
    width: 100%;
  }

  .orders-search .el-form-item .el-input,
  .orders-search .el-form-item .el-select,
  .orders-search .el-form-item .el-date-picker {
    width: 100% !important;
  }

  .el-pagination {
    justify-content: center;
    flex-wrap: wrap;
  }

  .el-pagination .el-pagination__total {
    margin: 0 0 10px 0;
    text-align: center;
    width: 100%;
  }
}
</style>